const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');

let users = {
  // "name": "password"
}

http.createServer((req, res) => {
  // console.log(req);
  // console.log(res);
  let path = null;
  let getData = {};
  let postData = {};
  console.log('method', req.method);
  console.log('url', req.url);

  if (req.method == 'GET') {

    let { pathname, query } = url.parse(req.url, true);
    path = pathname;
    getData = query;
    conplete()

  } else if (req.method == 'POST') {
    let arr = []
    path = req.url
    req.on('data', buffer => {
      console.log('buffer', buffer);
      arr.push(buffer);

    })
    req.on('end', () => {
      let buffer = Buffer.concat(arr)
      postData = querystring.parse(buffer.toString())
      conplete()
    })


  }

  function conplete() {
    console.log(path, getData, postData);
    if (path == '/reg') {
      let { userName, passWord } = getData;
      console.log('userName', userName);
      console.log('passWord', passWord);
      if (!userName) {
        res.write(JSON.stringify({ error: 1, msg: 'not kong' }));
        res.end()
      } else if (users[userName]) {
        res.write(JSON.stringify({ error: 1, msg: 'cunzaile' }))
        res.end()

      } else {
        users[userName] = passWord;
        res.write(JSON.stringify({ error: 0, msg: '' }))
        res.end()


      }

    } else if (path == '/login') {
      let { userName, passWord } = postData;
      console.log('userName', userName);
      console.log('passWord', passWord);
      if (!users[userName]) {
        res.write(JSON.stringify({ error: 1, msg: 'meiyou zhunce' }))
        res.end()

      } else if (users[userName] != passWord) {
        res.write(JSON.stringify({ error: 1, msg: 'mima budui' }))
        res.end()

      } else {
        res.write(JSON.stringify({ error: 0, msg: '' }))
        res.end()

      }


    } else {
      fs.readFile(`www${req.url}`, (err, data) => {
        if (err) {
          res.writeHeader(404);
          res.write('Not found');
          res.end()

        } else {
          res.write(data);
          res.end()

        }
      })

    }



  }

}).listen(2234)